package com.breeze.lib

import android.app.Activity
import android.app.Application
import android.os.Bundle
import android.view.LayoutInflater
import androidx.core.view.LayoutInflaterCompat
import java.lang.reflect.Field
import java.util.*

class MyActivityLifeCycleCallbacks(var observable: Observable) :
    Application.ActivityLifecycleCallbacks {
    private val TAG = "MyActivityLifeCycleCall"
    override fun onActivityPaused(activity: Activity) {
    }

    override fun onActivityStarted(activity: Activity) {
    }

    override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {
    }

    override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
        // 该方法在Activity的onCreate中会被回调，setContentView执行在该方法后，故可以选择在该方法中设置Factory2

//        var inflater = activity.layoutInflater
//        if (inflater.factory != null) {
//            inflater = inflater.cloneInContext(Activity)
//        }
//        inflater.factory = factory

        var layoutInflater = activity.layoutInflater
        try {
            //Android 布局加载器 使用 mFactorySet 标记是否设置过Factory
            //如设置过抛出异常
            //设置layoutInflater mFactorySet变量为false
            val field: Field = LayoutInflater::class.java.getDeclaredField("mFactorySet")
            field.isAccessible = true
            field.setBoolean(layoutInflater, false)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        var skinLayoutInflaterFactory = SkinLayoutInflaterFactory()
        // 设置自定义Factory2
//        layoutInflater.factory2 = skinLayoutInflaterFactory
        LayoutInflaterCompat.setFactory2(layoutInflater, skinLayoutInflaterFactory)
        observable.addObserver(skinLayoutInflaterFactory)



//        //使用自定义的Factory工厂
//        val layoutInflater = activity.layoutInflater
//        try {
//            val mFactorySet = LayoutInflater::class.java.getDeclaredField("mFactorySet")
//            mFactorySet.isAccessible = true
//            //防止第二次设置factory报错
//            mFactorySet.setBoolean(layoutInflater, false)
//        } catch (e: Exception) {
//            e.printStackTrace()
//        }
//        //加载字体
//        val typeface = SkinResources.getBackground(activity)
//        val factory = SkinLayoutInflaterFactory(activity, typeface)
//        layoutInflater.factory2 = factory
//        SkinManager.getInstance().addObserver(factory)
//        factoryMap[activity] = factory
    }

    override fun onActivityResumed(activity: Activity) {
    }

    override fun onActivityStopped(activity: Activity) {
    }

    override fun onActivityDestroyed(activity: Activity) {
    }
}